<template>
  <div class="document-version-manager">
    <n-card title="文档版本管理" :bordered="false">
      <template #header-extra>
        <n-space>
          <n-button type="primary" size="small" @click="createVersion">
            <template #icon>
              <AddOutline />
            </template>
            创建版本
          </n-button>
          <n-button size="small" @click="refreshVersions">
            <template #icon>
              <RefreshOutline />
            </template>
            刷新
          </n-button>
        </n-space>
      </template>
      
      <!-- 版本列表 -->
      <n-data-table
        :columns="columns"
        :data="versions"
        :pagination="pagination"
        :loading="loading"
        striped
        size="small"
      />
      
      <!-- 版本对比 -->
      <n-modal v-model:show="showCompareModal" preset="card" style="width: 90%; max-width: 1200px;">
        <template #header>版本对比</template>
        <div class="compare-container">
          <div class="compare-header">
            <n-space>
              <n-select
                v-model:value="compareVersion1"
                :options="versionOptions"
                placeholder="选择版本1"
                style="width: 200px;"
              />
              <span>VS</span>
              <n-select
                v-model:value="compareVersion2"
                :options="versionOptions"
                placeholder="选择版本2"
                style="width: 200px;"
              />
              <n-button type="primary" @click="compareVersions" :disabled="!compareVersion1 || !compareVersion2">
                对比
              </n-button>
            </n-space>
          </div>
          
          <div v-if="compareResult" class="compare-result">
            <n-tabs type="line">
              <n-tab-pane name="side-by-side" tab="并排对比">
                <div class="side-by-side-compare">
                  <div class="compare-panel">
                    <h3>版本 {{ getVersionLabel(compareVersion1 || '') }}</h3>
                    <div class="compare-content" v-html="compareResult.version1Content"></div>
                  </div>
                  <div class="compare-panel">
                    <h3>版本 {{ getVersionLabel(compareVersion2 || '') }}</h3>
                    <div class="compare-content" v-html="compareResult.version2Content"></div>
                  </div>
                </div>
              </n-tab-pane>
              <n-tab-pane name="diff" tab="差异视图">
                <div class="diff-view" v-html="compareResult.diffHtml"></div>
              </n-tab-pane>
            </n-tabs>
          </div>
        </div>
      </n-modal>
      
      <!-- 版本详情 -->
      <n-modal v-model:show="showVersionModal" preset="card" style="width: 80%; max-width: 800px;">
        <template #header>版本详情</template>
        <div v-if="selectedVersion" class="version-detail">
          <n-descriptions :column="2" bordered>
            <n-descriptions-item label="版本号">
              {{ selectedVersion.version }}
            </n-descriptions-item>
            <n-descriptions-item label="创建时间">
              {{ formatTime(selectedVersion.createTime) }}
            </n-descriptions-item>
            <n-descriptions-item label="创建人">
              {{ selectedVersion.creatorName }}
            </n-descriptions-item>
            <n-descriptions-item label="文件大小">
              {{ formatFileSize(selectedVersion.fileSize) }}
            </n-descriptions-item>
            <n-descriptions-item label="变更说明" :span="2">
              {{ selectedVersion.changeDescription || '无' }}
            </n-descriptions-item>
          </n-descriptions>
          
          <div class="version-content">
            <h3>内容预览</h3>
            <div class="content-preview" v-html="selectedVersion.contentPreview"></div>
          </div>
          
          <div class="version-actions">
            <n-space>
              <n-button type="primary" @click="restoreVersion(selectedVersion)">
                恢复此版本
              </n-button>
              <n-button @click="downloadVersion(selectedVersion)">
                下载此版本
              </n-button>
            </n-space>
          </div>
        </div>
      </n-modal>
      
      <!-- 创建版本 -->
      <n-modal v-model:show="showCreateModal" preset="card" style="width: 500px;">
        <template #header>创建新版本</template>
        <n-form
          ref="createFormRef"
          :model="createForm"
          :rules="createRules"
          label-placement="left"
          label-width="100px"
        >
          <n-form-item label="版本号" path="version">
            <n-input v-model:value="createForm.version" placeholder="请输入版本号，如 v1.0.1" />
          </n-form-item>
          <n-form-item label="变更说明" path="changeDescription">
            <n-input
              v-model:value="createForm.changeDescription"
              type="textarea"
              placeholder="请描述此版本的变更内容"
              :rows="4"
            />
          </n-form-item>
        </n-form>
        <template #footer>
          <n-space justify="end">
            <n-button @click="showCreateModal = false">取消</n-button>
            <n-button type="primary" @click="handleCreateVersion" :loading="createLoading">
              创建
            </n-button>
          </n-space>
        </template>
      </n-modal>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, h } from 'vue'
import { 
  NCard, NButton, NSpace, NDataTable, NModal, NSelect, NTabs, NTabPane, 
  NDescriptions, NDescriptionsItem, NForm, NFormItem, NInput, useMessage, NIcon
} from 'naive-ui'
import { AddOutline, RefreshOutline, EyeOutline, DownloadOutline, SyncOutline } from '@vicons/ionicons5'
import { formatTime } from '../../../utils/common'
import type { DataTableColumns } from 'naive-ui'

interface Props {
  documentId: string
}

defineProps<Props>()

const message = useMessage()

// 状态
const loading = ref(false)
const versions = ref<any[]>([])
const showCompareModal = ref(false)
const showVersionModal = ref(false)
const showCreateModal = ref(false)
const selectedVersion = ref<any>(null)
const compareVersion1 = ref<string | null>(null)
const compareVersion2 = ref<string | null>(null)
const compareResult = ref<any>(null)
const createLoading = ref(false)
const createFormRef = ref<any>(null)

// 表单数据
const createForm = ref({
  version: '',
  changeDescription: ''
})

// 表单验证规则
const createRules = {
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  changeDescription: [
    { required: true, message: '请输入变更说明', trigger: 'blur' }
  ]
}

// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})

// 版本选项
const versionOptions = computed(() => {
  return versions.value.map(version => ({
    label: `${version.version} (${formatTime(version.createTime)})`,
    value: version.id
  }))
})

// 表格列配置
const columns: DataTableColumns = [
  {
    title: '版本号',
    key: 'version',
    width: 120
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
    render: (row) => formatTime(row.createTime as string | number | Date)
  },
  {
    title: '创建人',
    key: 'creatorName',
    width: 120
  },
  {
    title: '文件大小',
    key: 'fileSize',
    width: 100,
    render: (row) => formatFileSize(row.fileSize as number | null)
  },
  {
    title: '变更说明',
    key: 'changeDescription',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    render: (row) => h(
      NSpace,
      { size: 'small' },
      {
        default: () => [
          h(
            NButton,
            {
              size: 'small',
              onClick: () => viewVersion(row)
            },
            () => [
              h(NIcon, null, () => h(EyeOutline)),
              '查看'
            ]
          ),
          h(
            NButton,
            {
              size: 'small',
              onClick: () => addToCompare(row.id as string)
            },
            () => '对比'
          ),
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              onClick: () => restoreVersion(row)
            },
            () => [
              h(NIcon, null, () => h(SyncOutline)),
              '恢复'
            ]
          ),
          h(
            NButton,
            {
              size: 'small',
              onClick: () => downloadVersion(row)
            },
            () => [
              h(NIcon, null, () => h(DownloadOutline)),
              '下载'
            ]
          )
        ]
      }
    )
  }
]

// 方法
const loadVersions = async () => {
  loading.value = true
  try {
    // 模拟版本数据，因为aiService中没有版本管理相关API
    const mockVersions = [
      {
        id: '1',
        version: 'v1.0.0',
        creatorName: '系统管理员',
        createTime: new Date('2023-01-01').getTime(),
        fileSize: 1024 * 100,
        changeDescription: '初始版本',
        contentPreview: '这是文档的初始版本内容...'
      },
      {
        id: '2',
        version: 'v1.1.0',
        creatorName: '张三',
        createTime: new Date('2023-02-15').getTime(),
        fileSize: 1024 * 150,
        changeDescription: '添加了新的章节和图片',
        contentPreview: '这是文档的第二个版本，新增了内容...'
      }
    ]
    
    versions.value = mockVersions
    pagination.value.itemCount = mockVersions.length
  } catch (error) {
    console.error('获取版本列表失败:', error);
    message.error('获取版本列表失败')
  } finally {
    loading.value = false
  }
}

const refreshVersions = () => {
  loadVersions()
}

const createVersion = () => {
  createForm.value = {
    version: '',
    changeDescription: ''
  }
  showCreateModal.value = true
}

const handleCreateVersion = async () => {
  try {
    await createFormRef.value?.validate()
    createLoading.value = true
    
    // 模拟创建版本，因为aiService中没有版本管理相关API
    message.success('版本创建成功')
    showCreateModal.value = false
    loadVersions()
  } catch (error) {
    console.error('创建版本失败:', error);
    message.error('创建版本失败')
  } finally {
    createLoading.value = false
  }
}

const viewVersion = (version: any) => {
  selectedVersion.value = version
  showVersionModal.value = true
}

const addToCompare = (versionId: string) => {
  if (!compareVersion1.value) {
    compareVersion1.value = versionId
  } else if (!compareVersion2.value && versionId !== compareVersion1.value) {
    compareVersion2.value = versionId
    showCompareModal.value = true
  } else {
    compareVersion1.value = versionId
    compareVersion2.value = null
  }
}

const compareVersions = async () => {
  if (!compareVersion1.value || !compareVersion2.value) {
    message.warning('请选择两个版本进行对比')
    return
  }
  
  try {
    // 模拟版本对比，因为aiService中没有版本管理相关API
    compareResult.value = {
      version1Content: '这是版本1的内容...',
      version2Content: '这是版本2的内容...',
      diffHtml: '<div class="diff-added">新增内容</div><div class="diff-removed">删除内容</div>'
    }
  } catch (error) {
    console.error('版本对比失败:', error);
    message.error('版本对比失败')
  }
}

const restoreVersion = async (_version: any) => {
  try {
    // 模拟版本恢复，因为aiService中没有版本管理相关API
    message.success('版本恢复成功')
    loadVersions()
  } catch (error) {
    console.error('版本恢复失败:', error);
    message.error('版本恢复失败')
  }
}

const downloadVersion = async (_version: any) => {
  try {
    // 模拟版本下载，因为aiService中没有版本管理相关API
    message.success('版本下载成功')
  } catch (error) {
    console.error('版本下载失败:', error);
    message.error('版本下载失败')
  }
}

const getVersionLabel = (versionId: string) => {
  const version = versions.value.find(v => v.id === versionId)
  return version ? version.version : ''
}

const formatFileSize = (bytes: number | null) => {
  if (!bytes || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 生命周期
onMounted(() => {
  loadVersions()
})
</script>

<style scoped>
.document-version-manager {
  margin-top: 16px;
}

.compare-container {
  min-height: 400px;
}

.compare-header {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.side-by-side-compare {
  display: flex;
  gap: 16px;
  height: 500px;
}

.compare-panel {
  flex: 1;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.compare-panel h3 {
  margin: 0;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.compare-content {
  flex: 1;
  padding: 16px;
  overflow: auto;
}

.diff-view {
  height: 500px;
  overflow: auto;
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.version-detail {
  margin-bottom: 16px;
}

.version-content {
  margin-top: 16px;
}

.version-content h3 {
  margin-bottom: 8px;
}

.content-preview {
  max-height: 300px;
  overflow: auto;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background-color: #f8f9fa;
}

.version-actions {
  margin-top: 16px;
  text-align: right;
}

/* 差异视图样式 */
.diff-view :deep(.diff-added) {
  background-color: #e6ffed;
}

.diff-view :deep(.diff-removed) {
  background-color: #ffeef0;
}

.diff-view :deep(.diff-changed) {
  background-color: #fff8c5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .side-by-side-compare {
    flex-direction: column;
    height: auto;
  }
  
  .compare-panel {
    height: 400px;
  }
}
</style>